package m.jclecai.com.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.adapter.BetJclqAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.dialog.BettingDialogFragment;
import m.jclecai.com.dialog.ShowOrderDialog;
import m.jclecai.com.listener.ISelectPlayListener;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.ui.JointPurchaseActivity;
import m.jclecai.com.utils.CalculateBetNums;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.utils.Utils;

import static m.jclecai.com.utils.CalculateBetNums.getBonus;
import static m.jclecai.com.utils.Utils.ZQ_ITEM_LIST;

public class BettingJCLQActivity extends BaseActivity implements MyNotifyTextViewSetChanged,
        View.OnClickListener,ISelectPlayListener {
    @BindView(R.id.tv_mid_title)
    TextView tv_mid_title;
    @BindView(R.id.rl_bar)
    RelativeLayout rl_bar;
    @BindView(R.id.include_term_stop_time)
    TextView include_term_stop_time;
    @BindView(R.id.include_listview)
    ListView include_listview;
    @BindView(R.id.include_bet_way)
    TextView include_bet_way;
    @BindView(R.id.include_multiple_context)
    EditText include_multiple_context;
    @BindView(R.id.toolbar_confirm)
    TextView toolbar_confirm;
    @BindView(R.id.tv_bonus)
    TextView tv_bonus;
    @BindView(R.id.tv_bonus_optimize)
    TextView tv_bonus_optimize;
    //注数
    int voteNums;
    //倍数
    String multiple;
    //是否有默认值要选中
    boolean check = true;
    //要选中的默认值过关方式
    private String pass="";
    //当前选中的过关方式 默认0为第一个
    private int currentDialoItemCheck = 0;
    BetJclqAdapter adapter;
    //详情见arrays.xml 对应 jczq_types_list 用于ui区分
    int pager = 0;
    int buyMoney = 0;
    //奖金优化
    String vote,name;

    private ShowOrderDialog mShowOrderDialog;

    @BindView(R.id.cb_saidan)
    CheckBox mCbBox;


    private String mSlogan;
    private String mWrate;
    private String mSunOrderMode;
    int itemCount = Utils.ZQ_ITEM_LIST.size();//过关串数

    @Override
    public int getContentView() {
        return R.layout.activity_betting_jczq;
    }


    @Override
    public void initView() {
        Intent intent = getIntent();
        pager = intent.getIntExtra("pager",0);
        name = intent.getStringExtra("name");
        setTitle(name);
        leftOptionText("添加");
        rightOptionText("发起合买");

        mShowOrderDialog = new ShowOrderDialog(this, new ShowOrderDialog.OnClickButtonListener() {

            @Override
            public void onClickSure(String mode, String profit, String slogan) {
                //确定;
                mSlogan = slogan;
                mWrate = profit;
                mSunOrderMode = mode;
                pay();
            }

            @Override
            public void onClickCancel() {
                //取消；
                mCbBox.setChecked(false);
            }
        },"10","10");
    }

    @OnClick({R.id.cb_saidan,R.id.toolbar_confirm})
    void onClickShowOrder(){
        //这里表示点击的了显示跟单；
        mShowOrderDialog.show(buyMoney+"",(buyMoney/Integer.parseInt(multiple))+"");
    }

    @Override
    public void initData() {
        adapter = new BetJclqAdapter(this,pager,this);
        View inflate = View.inflate(this,R.layout.lottery_list_footer,null);
        inflate.findViewById(R.id.betting_item_footer_clear).setOnClickListener(this);
        inflate.findViewById(R.id.betting_item_footer_check).setOnClickListener(this);
        include_listview.addFooterView(inflate);
        //低版本 addFooterView需要在setAdapter前面
        include_listview.setAdapter(adapter);
        String[] names = getResources().getStringArray(R.array.lottery_pass_types_name_list);
        names = StringUtils.filterData(names,"串",getItemCount(),adapter.getCheckDan(),isDG());
        //默认选中的过关方式
        if(names != null && names.length>0){
            pass = names[names.length - 1];
        }else{
            if(isDG()){
                pass="单关";
            }else{
                pass="2串1";
            }
        }
        include_bet_way.setText(pass.replaceAll("1串1","单关"));
        getPredictBonus();
    }

    //过关串数
    public int getItemCount(){
        itemCount = Utils.ZQ_ITEM_LIST.size();
        //含有比分玩法的，场次超过4场，最大过关 必须变成 4串1
        //含有半全场玩法的，场次超过4场，最大过关 必须变成 4串1
        //含有进球数玩法的，场次超过6场，最大过关 必须变成 6串1
        if(Utils.ZQ_ITEM_LIST.size() >= 4){
            for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
                // 5 - 胜分差
                if(Utils.ZQ_ITEM_LIST.get(i).getMap().containsKey("5")){
                    itemCount = 4;
                }
            }
        }
        return itemCount;
    }



    //过关倍数
    @OnTextChanged(R.id.include_multiple_context)
    void multiple(Editable s){
        Log.e("bs",s.toString());
        if(TextUtils.isEmpty(include_multiple_context.getText().toString())){
            return;
        }
        if ("0".equals(s.toString())){
            include_multiple_context.setText("1");
            include_multiple_context.setSelection(1);
            getPredictBonus();
            return;
        }
        getPredictBonus();
    }

    //过关方式
    @OnClick(R.id.include_bet_way)
    void showPassType() {
        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            return;
        }
        BettingDialogFragment dialogFragment = new BettingDialogFragment();
        dialogFragment.show(getSupportFragmentManager(), "Dialog");
        dialogFragment.setItemCount(getItemCount());
        dialogFragment.setListener(this);
        dialogFragment.setDG(isDG());
        dialogFragment.setDefCheck(check,pass,currentDialoItemCheck);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.betting_item_footer_clear:
                if(ZQ_ITEM_LIST.size() > 0)
                    showAlertDialog("提示","确认清空所有数据?","取消","确认",null,new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ZQ_ITEM_LIST.clear();
                            adapter.notifyDataSetChanged();
                        }
                    });
                break;
            case R.id.betting_item_footer_check:
                startActivity(LotteryProtocolActivity.getIntent(this));
                break;
        }
    }

    //支付
//    @OnClick(R.id.toolbar_confirm)
    void pay(){
        if (TextUtils.isEmpty(include_multiple_context.getText().toString())) {
            include_multiple_context.setText("1");
            include_multiple_context.setSelection(1);
            getPredictBonus();
        }

        if(TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }
        /**
         * 此处提交之前先判断用户是否登录
         * 竞彩类 北京单场 只有混投调用balls  其余单关 混投奖金优化 其余奖金优化 其他栏目调用ball
         * 所以混合投注 做一个标识区分开减少判断逻辑
         *
         * 新增玩法单关玩法下
         * 如果过关方式仅仅只选择 单关 ==》 1*1  ball.php 单独过关方式
         * =================================================
         * 如果过关方式选择 单关,2*1,3*1 ==》 单关 =>1*1   balls.php 这里指其余过关方式
         * 如果过关方式选择 2*1,3*1 ==》   balls.php
         */
        String stringCode = StringUtils.getBonus(Utils.ZQ_ITEM_LIST,pass,(pager == 3||pager == 5));
        Log.e("stringCode",stringCode);
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(voteNums));
        intent.putExtra(PAY_MULTIPLE,multiple);
        intent.putExtra(PAY_MONEY, String.valueOf(buyMoney));
        intent.putExtra(PAY_CODES,stringCode);
        intent.putExtra(PAY_TYPE,"jclq");
        intent.putExtra(PAY_PASS,pass.replaceAll("串","*").replaceAll("单关","1*1"));
        intent.putExtra(PAY_LOTTERY_TYPE,name);
        //是否调用balls 接口
        intent.putExtra(PAY_LOTTERY_BALLS, "混合投注".equals(name) || (name.contains("单关") && !"单关".equals(pass)));

        intent.putExtra(SUN_ORDER_MODE, mSunOrderMode);
        intent.putExtra(SUN_ORDER_SLOGAN, mSlogan);
        intent.putExtra(PAY_WRATE, mWrate);
        intent.putExtra(IS_SHOW_ORDER, mCbBox.isChecked()?"1":"0");
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    //奖金优化
    @OnClick(R.id.ll_bonus_optimize)
    void bonusOptimize(){
        if(TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }
        String stringCode = StringUtils.getBonusAward(Utils.ZQ_ITEM_LIST,pass,(pager == 3||pager == 5));

        startActivityForResult(new Intent(this,BonusOptimizationActivity.class)
                        .putExtra("codes",stringCode)
                        .putExtra("vote",vote)
                        .putExtra("pass",pass.replaceAll("串","*").replaceAll("单关","1*1"))
                        .putExtra("money",buyMoney)
                        .putExtra(PAY_LOTTERY_TYPE,name)
                        .putExtra(PAY_MULTIPLE,multiple)
                        .putExtra(PAY_VOTENUMS, String.valueOf(voteNums))
                        .putExtra(PAY_TYPE,"jclq")
                        .putExtra(PAY_TYPE_NUM,getPlayType())
                        .putExtra(PAY_TERM,getTerm())
                ,Constant_Result.CLOSEPAGE);
    }

    /**
     * 这里是获取期号；
     * @return
     */
    private String getTerm() {
        ZqItem zqItem = Utils.ZQ_ITEM_LIST.get(0);
        String term = zqItem.getCodes()[0];
        return term.substring(0,term.length()-3);
    }


    /**
     * 获取playType；
     * @return
     */
    private String getPlayType() {


       /* <item>胜负</item>
        <item>让分胜负</item>
        <item>大小分</item>
        <item>混合投注</item>
        <item>胜分差</item>
        <item>竞篮单关</item>*/

        if (name.equals("胜负")) {

            return "51";

        }else if(name.equals("让分胜负")){

            return "52";

        }else if(name.equals("大小分")){

            return "54";

        } else if ("混合投注".equals(name)) {

            return "55";

        }else if("胜分差".equals(name)){

            return "53";

        } else if ("单关".equals(name)) {

            return "56";
        }

        return "51";
    }


    /**
     * 预测奖金
     */
    private void getPredictBonus() {
        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        //算预测奖金
        try{
            vote = StringUtils.getBonusCode(Utils.ZQ_ITEM_LIST);
            Log.e("getBonusCode",vote);
            if(TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)){
                MyToast.showToast(getBaseContext(),"请选择过关方式");
                return;
            }
            String buyType = pass.replaceAll("串","*");
            buyType = buyType.replaceAll("单关","1*1");
            CalculateBetNums calculateBetNums = new CalculateBetNums();
            //得到的是注数
            voteNums = calculateBetNums.getVoteNums(vote, buyType);
            List<String> rebuildVote = CalculateBetNums.rebuildVote(vote, buyType);
            String sp_max = getBonus(rebuildVote, 1, 1);//最大奖金
            String sp_min = getBonus(rebuildVote, 0, 1);//最小奖金
            multiple = include_multiple_context.getText().toString().trim();
            int num = Integer.parseInt(multiple);

            //这里我们对最小，最大金额进行一个调整的操作；

            float spMin = Float.parseFloat(sp_min);
            float vMin = num * spMin;
            String minStr="";
            String maxStr="";
            if(vMin == Float.POSITIVE_INFINITY||vMin ==Float.NEGATIVE_INFINITY){
                minStr="0.00";
            }else{
                minStr=vMin+"";
            }

            float vMax = num * Float.parseFloat(sp_max);

            if(vMax == Float.POSITIVE_INFINITY||vMax ==Float.NEGATIVE_INFINITY){
                maxStr="0.00";
            }else{
                maxStr=vMax+"";
            }

            String money = minStr + "~" + maxStr;

            buyMoney = (voteNums * num * 2);
            String txt = String.format(getString(R.string.jc_bonus_optimiiza),voteNums,num,buyMoney,money);
            tv_bonus.setText(Html.fromHtml(txt));

        }catch (Exception e){
            MyToast.showToast(getBaseContext(),"计算异常");
            e.printStackTrace();
        }
    }

    //支持单关的小蓝点
    boolean isDG(){
        boolean isDG = false;
        for (int i=0;i<ZQ_ITEM_LIST.size();i++){
            String value = ZQ_ITEM_LIST.get(i).getCodes()[18];
            int dValue = TextUtils.isEmpty(value) ? 0 : Integer.parseInt(value);
            StringBuilder sb = new StringBuilder();
            //解析成二进制串 支持单关标志1 不支持标志0
            String s = Integer.toBinaryString(dValue);
            //因为篮球有4个玩法 计算顺序为
            //胜负 让份胜负 胜分差 大小分
            //  0      0       1     1
            //其中总进球 比分 半全场 永远支持单关
            //因为我是直接从左往右拆分二进制
            int num = 4 - s.length();
            //num 是需要补齐位数 默认补齐0 例如7 = 111  补齐为0111
            //所以左->右前两个玩法为0 不支持单关
            for (int j = 0; j < num; j++) {
                //补齐位数 默认补齐0
                sb.append("0");
            }
            sb.append(s);
            //    胜负       让份胜负      大小分       胜分差
            switch (pager){
                case 0:
                    isDG = "1".equals(String.valueOf(sb.charAt(0)));
                    break;
                case 1:
                    isDG = "1".equals(String.valueOf(sb.charAt(1)));
                    break;
                case 2:
                    isDG = "1".equals(String.valueOf(sb.charAt(3)));
                    break;
                case 4:
                    isDG = "1".equals(String.valueOf(sb.charAt(2)));
                    break;
            }
            if(pager == 5) isDG = true;
            if(pager == 2 ){ isDG=false;}
            if (!isDG) break;
        }
        return isDG;
    }

    @Override
    public void onClickSetChangedText() {
        tv_bonus.setText("");
        include_bet_way.setText("过关方式");
        this.pass = "";
        adapter.notifyDataSetChanged();
    }

    @Override
    public void refreshData() {
        tv_bonus.setText("");
        include_bet_way.setText("过关方式");
        this.pass = "";
        adapter.notifyDataSetChanged();
    }

    @Override
    public void select(String value, int itemPosition) {
        currentDialoItemCheck = itemPosition;
        this.pass = value;
        check = !TextUtils.isEmpty(value);
        if (TextUtils.isEmpty(value)) {
            include_bet_way.setText("过关方式");
            tv_bonus.setText("");
        } else{
            include_bet_way.setText(value.replaceAll("1串1", "单关")
                    .replaceAll("[*]", "串"));
        }
        getPredictBonus();
    }

    //合买
    @OnClick(R.id.tv_right_option)
    void jointPurchase() {
        if(Utils.ZQ_ITEM_LIST.size() < 2 && !isDG()){
            MyToast.showToast(this,"至少选择2场比赛");
            tv_bonus.setText("");
            include_bet_way.setText("过关方式");
            this.pass = "";
            return;
        }
        if(TextUtils.isEmpty(vote) || TextUtils.isEmpty(pass)){
            MyToast.showToast(getBaseContext(),"请选择过关方式");
            return;
        }

        Integer multiple = 1;
        try {
            multiple=Integer.valueOf(this.multiple);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        String stringCode = StringUtils.getBonus(Utils.ZQ_ITEM_LIST,pass,(pager == 3||pager == 5));
        Intent intent = new Intent(this, JointPurchaseActivity.class);
        intent.putExtra("totalNum",voteNums);
        intent.putExtra("multiple", multiple);
        intent.putExtra("totalMoney", buyMoney);
        intent.putExtra("num", 1);
        intent.putExtra(PAY_TYPE, "jclq");
        intent.putExtra(PAY_CODES, stringCode+";");//因为JointPurchaseActivity code会-1
        intent.putExtra(PAY_NAME, "合买");
        startActivityForResult(intent,Constant_Result.CLOSEPAGE);
    }

    @Override
    protected void close(){
        finish();
    }
}
